package com.zzy.mccjt.service.common.framework.constants;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * description:
 *
 * @author zzy
 * @version 1.0
 * @date 2020/4/16
 */
@Slf4j
@Data
public class ContextUserLocal {
    /***用户token*/
    private String token;
    /***租户ID*/
    private Integer tenantId;
    /***请求的服务版本号*/
    private String version;
    /***用户JSON信息*/
    private String loginUser;
    /***是否需要处理逻辑删除SQL*/
    private Boolean isNeedLogicDelete;

    private static ThreadLocal<ContextUserLocal> CURRENT_LOCAL = new InheritableThreadLocal<>();


    private void setTenantId(Integer tenantId) {
        this.tenantId = tenantId == null ? null : Math.abs(tenantId);
    }


    public static void init(String token, Integer tenantId) {
        ContextUserLocal contextUserLocal = new ContextUserLocal();
        contextUserLocal.setToken(token);
        contextUserLocal.setTenantId(tenantId);
        set(contextUserLocal);
    }

    public static void init(String token, Integer tenantId, String loginUser) {
        ContextUserLocal contextUserLocal = new ContextUserLocal();
        contextUserLocal.setToken(token);
        contextUserLocal.setTenantId(tenantId);
        contextUserLocal.setLoginUser(loginUser);
        set(contextUserLocal);
    }

    public static void init(String token, Integer tenantId, String loginUser, String version) {
        ContextUserLocal contextUserLocal = new ContextUserLocal();
        contextUserLocal.setToken(token);
        contextUserLocal.setTenantId(tenantId);
        contextUserLocal.setLoginUser(loginUser);
        contextUserLocal.setVersion(version);
        set(contextUserLocal);
    }


    public static ContextUserLocal get() {
        ContextUserLocal contextUserLocal = CURRENT_LOCAL.get();
        log.debug(Thread.currentThread().getName() + " ContextUserLocal.get {}", contextUserLocal);
        return contextUserLocal;
    }

    public static void set(ContextUserLocal contextUserLocal) {
        log.debug(Thread.currentThread().getName() + " ContextUserLocal.set {}", contextUserLocal);
        CURRENT_LOCAL.set(contextUserLocal);
    }

    public static void remove() {
        log.debug(Thread.currentThread().getName() + " ContextUserLocal.remove {}");
        //防止内存泄漏
        CURRENT_LOCAL.remove();
    }
}
